package com.fzx.fzwsupplysystem.util;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 描述：
 * 项目名称：AndroidUtilsDemo
 * 创建人：  FangZhixin
 * 创建时间：2018/9/25
 */
public class MyPermission {

    private static String TAG = "MyPermission";
    private static final int REQUEST_CODE_PERMISSION = 999;
    private static OnPermissionCallback mPermissionCallback;
    private static AlertDialog alertDialog;

    public interface OnPermissionCallback {

        void onSuccess();

        void onGranted(List<String> permissions);

        void onDenied(List<String> permissions);

    }

    /**
     * 检测是否有权限
     *
     * @param context    上下文
     * @param permission String，权限
     * @return boolean
     */
    public static boolean hasPermission(Context context, String permission) {
        return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
    }

    /**
     * 根据包名判断应用权限是否有授权
     *
     * @param context    上下文
     * @param pkgName    包名
     * @param permission 权限，Manifest.permission.WRITE_EXTERNAL_STORAGE
     * @return boolean，是否有权限
     */
    public static boolean hasPermission(Context context, String pkgName, String permission) {
        PackageManager packageManager = context.getPackageManager();
        try {
            PackageInfo pkgInfo = packageManager.getPackageInfo(pkgName, PackageManager.GET_PERMISSIONS);
            String[] permissions = pkgInfo.requestedPermissions;
            Log.i(TAG, "hasPermission: " + Arrays.toString(permissions));
            for (int i = 0; i < permissions.length; i++) {
                if (permission.equals(permissions[i])) {
                    return PackageManager.PERMISSION_GRANTED == packageManager.checkPermission(permissions[i], pkgName);
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 获取应用获取的权限
     *
     * @param context 上下文
     * @param pkgName 包名
     * @return String[]，权限数组
     */
    public static String[] getPermission(Context context, String pkgName) {
        PackageManager packageManager = context.getPackageManager();
        try {
            PackageInfo pkgInfo = packageManager.getPackageInfo(pkgName, PackageManager.GET_PERMISSIONS);
            String[] permissions = pkgInfo.requestedPermissions;
            Log.i(TAG, "hasPermission: " + Arrays.toString(permissions));
            return permissions;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 是否选择再次询问授权
     *
     * @param context    上下文
     * @param permission 权限
     * @return boolean
     */
    public static boolean shouldShowRequestPermissionRationale(Activity context, String permission) {
        //若有些权限选择了不再询问，则返回false
        return ActivityCompat.shouldShowRequestPermissionRationale(context, permission);
    }


    public static void showPermissionSettingDialog(final Context context) {
        if (alertDialog != null && alertDialog.isShowing()) {
            alertDialog.dismiss();
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setPositiveButton("前往", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                goPermissionSetting(context);
            }
        });
        alertDialog = builder.setTitle("提示").setMessage("未获取到相应权限，是否前往授权设置页面进行授权").create();
        alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.show();
    }

    public static void closePermissionSettingDialog() {
        if (alertDialog != null && alertDialog.isShowing()) {
            alertDialog.dismiss();
        }
    }

    /**
     * 进入系统设置权限
     *
     * @param context 上下文
     */
    public static void goPermissionSetting(Context context) {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", context.getPackageName(), null);
        intent.setData(uri);
        context.startActivity(intent);

    }

    public static void requestPermission(Activity context, String permission) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!hasPermission(context, permission)) {
                ActivityCompat.requestPermissions(context, new String[]{permission}, REQUEST_CODE_PERMISSION);
            }
        }
    }

    /**
     * 请求单一权限，需要在Activity实现onRequestPermissionsResult方法
     *
     * @param callback   权限回调
     * @param context    Activity
     * @param permission 权限
     */
    public static void requestPermission(OnPermissionCallback callback, Activity context, String permission) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            mPermissionCallback = callback;
            if (!hasPermission(context, permission)) {
                ActivityCompat.requestPermissions(context, new String[]{permission}, REQUEST_CODE_PERMISSION);
            } else {
                List<String> hasGrantedList = new ArrayList<>();//已授权
                hasGrantedList.add(permission);
                if (callback != null) {
                    callback.onSuccess();
                    callback.onGranted(hasGrantedList);
                }
            }
        } else {
            if (callback != null) {
                callback.onSuccess();
            }
        }
    }

    public static void requestMultiPermission(Activity context, String... permissions) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> needGrantedList = new ArrayList<>();//需要授权
            for (String permission : permissions) {
                if (!hasPermission(context, permission)) {//没授权
                    needGrantedList.add(permission);
                }
            }
            if (needGrantedList.size() > 0) {
                String[] p = new String[needGrantedList.size()];
                ActivityCompat.requestPermissions(context, needGrantedList.toArray(p), REQUEST_CODE_PERMISSION);
            }
        }
    }

    /**
     * 请求多个权限，需要在Activity实现onRequestPermissionsResult方法
     *
     * @param callback    权限回调
     * @param context     Activity
     * @param permissions 权限数组
     */
    public static void requestMultiPermission(OnPermissionCallback callback, Activity context, String... permissions) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            mPermissionCallback = callback;
            List<String> needGrantedList = new ArrayList<>();//需要授权
            List<String> hasGrantedList = new ArrayList<>();//已授权
            for (String permission : permissions) {
                if (hasPermission(context, permission)) {//已授权
                    hasGrantedList.add(permission);
                } else {//没权限
                    needGrantedList.add(permission);
                }
            }
            if (needGrantedList.size() <= 0 && callback != null) {
                callback.onSuccess();
                callback.onGranted(hasGrantedList);
            } else {
                String[] p = new String[needGrantedList.size()];
                ActivityCompat.requestPermissions(context, needGrantedList.toArray(p), REQUEST_CODE_PERMISSION);
            }
        } else {
            if (callback != null) {
                callback.onSuccess();
            }
        }
    }

    /**
     * 在activity中实现的onRequestPermissionsResult方法中直接调用
     *
     * @param requestCode  请求码
     * @param permissions  权限数组
     * @param grantResults 是否授权
     */
    public static void requestPermissionResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_PERMISSION:
                List<String> grants = new ArrayList<>();
                List<String> denies = new ArrayList<>();
                for (int i = 0; i < grantResults.length; i++) {
                    Log.i(TAG, "requestPermissionResult: grantResults[i]=" + grantResults[i]);
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        Log.i(TAG, "onRequestPermissionsResult: " + permissions[i] + "授权成功");
                        grants.add(permissions[i]);
                    } else {
                        denies.add(permissions[i]);
                        Log.i(TAG, "onRequestPermissionsResult: " + permissions[i] + "授权失败");
                    }
                }
                if (mPermissionCallback != null) {
                    if (grants.size() == grantResults.length) {
                        mPermissionCallback.onSuccess();
                    }
                    if (grants.size() > 0) {
                        mPermissionCallback.onGranted(grants);
                    }
                    if (denies.size() > 0) {
                        mPermissionCallback.onDenied(denies);
                    }
                }
                break;
            default:
                break;
        }
    }

}
